<?php
class Delivery_Model_DbTable_Categorias
	extends Delivery_Model_DbTable_Abstract

{
	protected $_name = 'categorias';
	protected $_primary = 'idCategoria';
	
	public function insert( $categoria ){
		
		return parent::insert(		
			array ('nombre'	=> $categoria->nombre, 'nombreSingular'	=> $categoria->nombreSingular) 
		);	
	}
	
	public function update( $categoria ){
		
		return parent::update(
			array ('nombre'	=> $categoria->nombre, 'nombreSingular'	=> $categoria->nombreSingular)  ,
			array('idCategoria = ?' => $categoria->idCategoria)
		
		);
	}
	
	public function delete( $categoria ){
		return parent::delete(
			array( 'idCategoria = ?' => $categoria->idCategoria)
		);
	}
	
	public function getById( $idCategoria ){
		
		return 
			$this->_db->fetchRow(
				$this->select()->where('idCategoria = ?', $idCategoria, Zend_Db::INT_TYPE)
			);
	}
	
	/**
	 * @param array $ids
	 * @return array:
	 */
	public function getByIds( $ids )
	{
		return $this->getAdapter()->fetchAll(
			$this->select()->where( 'idCategoria IN (?)', $ids, Zend_Db::INT_TYPE),
			null,
			Zend_Db::FETCH_ASSOC
		);		
	}
	
	/**
	 * @param array $ids
	 * @return array:
	 */
	public function getByNegocio( $idNegocio )
	{
//	    SELECT * 
//        FROM categorias c 
//        WHERE idCategoria in (
//        	Select distinct idCategoria from productos where idNegocio = 2
//        )
	    
	    
        $select1 = parent::select( self::SELECT_WITHOUT_FROM_PART)
                    ->setIntegrityCheck(false)
					->from( 'productos', array('idCategoria'))
					->distinct()
					->where('idNegocio = ?', $idNegocio); 
	    
	    $select1 = $select1->assemble();
	    
		return $this->getAdapter()->fetchAll(
			$this->select()->where( "idCategoria IN ( $select1 )" ),
			null,
			Zend_Db::FETCH_ASSOC
		);		
		
	}
	
	public function getAll(){
					
		return 
			$this->_db->fetchAssoc(
				$this->select()					
			);
	}
	
	public function getByParams( $params, $offset = null, $limit = null, $order = null ){
		
		$select = $this->select();
			
		if ( $order ){
			$select->order( $order );
		}
		
		if ( $limit && !is_null($offset) ){
			$select->limit( $limit, $offset );
		}
		
		return $this->_db->fetchAssoc($select);
	}
	
	public function countByParams( $params )
	{
		$select = $this->select();
		
		$results = $this->_db->fetchAssoc($select);
		
		return count($results);
	}
	
	
}